<div id="jigou_manage">
    <div class="jigou_manage">
        <div>
            <ul id="treeDemo" class="ztree"></ul>
            <button  class="addUsrtBtn" @click="goAdddialog" v-if="isShowAddBtnInfo">+导入机构</button>

        </div>
        <div class="isShowingBox" v-show="isShowingBox"></div>
        <el-dialog title="增加机构" :visible.sync="dialogFormVisible" :close-on-click-modal="ismodalClose" :show-close="showDelBtn">
            <span class="delDialogBtn" @click="closeAddDialog">x</span>
        <el-row>
        <el-col :span="12" style="position: relative">
        <span>请选择机构模板文件：</span>
            <div id="uploadArea" style=" text-align: center;">
            <form id="uploadForm" action="" method="post" enctype="multipart/form-data" name="fileForm">
                <input id="fileArea" type="file" name="file" @change="filesChange">
                <!--<input type="button" onclick="ajaxSubmitForm();" value="确定">-->
                <button type="button" class="layui-btn" id="liulan"  >浏览</button>
                <div class="showFileName">{{fileNameModel}}</div>
            </form>
        </div>
        </el-col>
        <el-col :span="12" style="padding-left: 50px">
        <a class="pullAllTemp" href="javascript:void(0)" @click="pullAllInfo">下载批量模板</a>
        </el-col>
        </el-row>

        <div slot="footer" class="dialog-footer">
            <el-button @click="backHome">取 消</el-button>
            <el-button type="primary" @click="ajaxSubmitForm">确 定</el-button>
        </div>
        </el-dialog>

    </div>
</div>

<script>


    var layer,
        loadJigou;
    layui.use('layer', function(){
        layer = layui.layer;
        loadJigou  = layer.load(1, {shade: [0.5, '#000']});
    });

    var setting = {

        check: {
            enable: false
        },
        view: {
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        edit: {
            enable: true,
            editNameSelectAll: true,
            showRemoveBtn: showRemoveBtn,
            removeTitle :"删除",
            renameTitle :"修改"

        },
        data: {
            simpleData: {
                enable: true
            },
            keep: {
                parent: true,
            },
        },
        callback: {
            beforeDrag: beforeDrag,
            beforeEditName: beforeEditName,
            beforeRemove: beforeRemove,
            beforeRename: beforeRename,
            onRemove: onRemove,
            onRename: onRename,
            onCheck: onCheck
        },
        simpleData: {
            //是否使用简单数据模式
            enable: true,
            //当前节点id属性
            idKey: "id",
            //当前节点的父节点id属性
            pIdKey: "pId",
            //用于修正根节点父节点数据，即pIdKey指定的属性值
            rootPId: 0
        }
    };
    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        for (var i=0, l=childNodes.length; i<l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
        }
        return childNodes;
    }
    var zNodes =[];
    var log, className = "dark";
    var clearFlag = false;
    function onCheck(e, treeId, treeNode) {
        //count();
        if (clearFlag) {
            clearCheckedOldNodes();
        }
    }
    function beforeDrag(treeId, treeNodes) {
        return false;
    }
    function beforeEditName(treeId, treeNode) {
        className = (className === "dark" ? "":"dark");
        showLog("[ "+getTime()+" beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.selectNode(treeNode);
        setTimeout(function() {
            //if (confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？")) {
            // setTimeout(function() {
            zTree.editName(treeNode);
            // }, 0);
            // }
        }, 0);
        return false;
    }
    function beforeRemove(treeId, treeNode) {
        className = (className === "dark" ? "":"dark");
        showLog("[ "+getTime()+" beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.selectNode(treeNode);
        if(treeNode.children){
            jigou_manage.$message.error('请先删除子机构！');
            return false
        }
        return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
    }
    function onRemove(e, treeId, treeNode) {
        showLog("[ "+getTime()+" onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var options= {deptId:treeNode.id};
        sendService('${basePath}/merchant/dept/deleteDept', options, function (resData) {
            if(resData.status == 'success'){
                reloadPage('${basePath}merchant/dept/toDeptTree');
                layer.msg(resData.msg, {icon: 6});
            }else {
                reloadPage('${basePath}merchant/dept/toDeptTree');
                layer.msg(resData.msg, {icon: 2});
            }
        })
    }
    function beforeRename(treeId, treeNode, newName, isCancel) {
        sessionStorage.oldName = treeNode.name;
        className = (className === "dark" ? "":"dark");
        showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));

        if (newName.length == 0) {
            setTimeout(function() {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.cancelEditName();
                alert("节点名称不能为空.");
            }, 0);
            return false;
        }
        return true;
    }
    function onRename(e,treeId, treeNode, isCancel) {
        showLog((isCancel ? "<span style='color:red'>":"") + "[ "+getTime()+" onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>":""));
        var isDeptName = sessionStorage.deptName;
        var isDeptId = sessionStorage.deptId;
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var treeNodesRef1 = treeObj.getSelectedNodes();
        var node2333 = treeObj.getNodeByParam("id",treeNode.pId );
        if(treeNode.name == isDeptName || treeNode.id == isDeptId){
            sessionStorage.removeItem("deptName");
            sessionStorage.removeItem("deptId");
            var options2= {deptId:treeNode.pId,cName:treeNode.name};
            sendService('${basePath}/merchant/dept/saveDept', options2, function (resData) {
                if(resData.status == 'success'){
                    layer.msg(resData.msg, {icon: 6});
                    isShowAddBtn = true;
                    //treeObj.updateNode(treeNodesRef1[0]);
                    reloadPage('${basePath}merchant/dept/toDeptTree');
                }else {
                    isShowAddBtn = true;
                    layer.msg(resData.msg, {icon: 2});
                    reloadPage('${basePath}merchant/dept/toDeptTree');
                }
            })
            return
        }
        if(sessionStorage.oldName == treeNode.name){
            return
        }else {
            var options1= {deptId:treeNode.id,name:treeNode.name};
            sendService('${basePath}/merchant/dept/UpdateDept', options1, function (resData) {
                //console.log(options1)
                if(resData.status == 'success'){
//                    jigou_manage.$message({
//                        type: 'success',
//                        message: resData.msg
//                    });
                    isShowAddBtn = true;
                    //treeObj.updateNode(treeNodesRef1[0]);
                    reloadPage('${basePath}merchant/dept/toDeptTree');
                }else {
                    layer.msg(resData.msg, {icon: 2});
                    isShowAddBtn = true;
                    // treeObj.selectNode(node2333)
                    // treeObj.reAsyncChildNodes(node2333, "refresh");

                    //treeObj.updateNode(node2333);
                    //treeObj.reAsyncChildNodes(node2333, "refresh");
                    reloadPage('${basePath}merchant/dept/toDeptTree');
                }
            })
        }

    }
    function showRemoveBtn(treeId, treeNode) {
        //return !treeNode.isFirstNode;
        if(treeNode.level == 0){
            return false;
        }else{
            return true;
        }
    }
    function showRenameBtn(treeId, treeNode) {
        //return !treeNode.isLastNode;
        if(treeNode.level == 0){
            return false;
        }else{
            return true;
        }
    }
    function showLog(str) {
        if (!log) log = $("#log");
        log.append("<li class='"+className+"'>"+str+"</li>");
        if(log.children("li").length > 8) {
            log.get(0).removeChild(log.children("li")[0]);
        }
    }
    function getTime() {
        var now= new Date(),
            h=now.getHours(),
            m=now.getMinutes(),
            s=now.getSeconds(),
            ms=now.getMilliseconds();
        return (h+":"+m+":"+s+ " " +ms);
    }
    var isShowAddBtn = true;
    var newCount = 1;
    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        if(isShowAddBtn){
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='添加' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", {isParent:false},function(e){
                isShowAddBtn = false;
                var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
                    isParent = e.data.isParent,
                    nodes = zTree.getSelectedNodes(),
                    treeNode2333 = nodes[0];
                if(nodes.length == 0){
                    isShowAddBtn = true;
                    alert("请先选择一个节点");
                    return
                }
                if (treeNode2333) {
                    treeNode2333 = zTree.addNodes(treeNode2333, {id:parseInt(Math.random() * 1000000), pId:treeNode2333.id, isParent:isParent, name:"未命名"});
                } else {
                    treeNode2333 = zTree.addNodes(null, {id:parseInt(Math.random() * 1000000), pId:0, isParent:isParent, name:"未命名"});
                }
                if (treeNode2333) {
                    zTree.editName(treeNode2333[0]);
                } else {
                    alert("叶子节点被锁定，无法增加子节点");
                }
                sessionStorage.deptName = treeNode2333[0].name;
                sessionStorage.deptId = treeNode2333[0].id;

                return false;
            });

        }

    };
    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    };
    function selectAll() {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.setting.edit.editNameSelectAll =  $("#selectAll").attr("checked");
    }

    var jigou_manage = new Vue({
        el:'#jigou_manage',
        data:{
            isShowingBox:false,
            showDelBtn:false,
            fileNameModel:'',


            ismodalClose:false,
            fileList:[],
            ztreeData:'',
            isShowAddBtnInfo:'',

            dialogFormVisible: false,
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            formLabelWidth: '120px'
        },
        methods:{
            filesChange:function () {
                var nameFlis = $("#fileArea").val();
                var fileName123 = nameFlis.split("\\");
                this.fileNameModel = fileName123[fileName123.length-1];
            },
            backHome:function () {
                this.closeAddDialog();
                this.isShowingBox = false;
                this.dialogFormVisible = false;
            },
            /**
             * 点击X关闭模态框
             * */
            closeAddDialog:function () {
                this.fileNameModel = '';
                this.isShowingBox = false;
                this.dialogFormVisible = false;
            },
            ajaxSubmitForm:function() {
                var that = this;
                var option = {
                    url : '${basePath}merchant/dept/upload',
                    type : 'POST',
                    dataType : 'json',
                    headers : {"ClientCallMode" : "ajax"}, //添加请求头部
                    success : function(data) {
                        that.fileNameModel = '';
                        that.backHome();
                        if(data.status == 'success'){
                            layer.msg(data[0].msg, {icon: 6});
                            $(".main-right").empty();
                            $(".main-right").load('${basePath}/jigouIE9');
                        }else{
                            layer.msg(data[0].msg, {icon: 6});
                            $(".main-right").empty();
                            $(".main-right").load('${basePath}/jigouIE9');
                            return;
                        }
                    },
                    error: function(data) {
                        $(".main-right").empty();
                        $(".main-right").load('${basePath}/jigouIE9');
                        layer.msg(data.msg, {icon: 2});
                    }
        };
        $("#uploadForm").ajaxSubmit(option);
//        $(".main-right").empty();
//        $(".main-right").load('${basePath}/jigouIE9');
        return false;
    },
            /**
             * 批量下载模板
             */
            pullAllInfo:function () {
                window.location.href="${basePath}/merchant/dept/download";
            },
            goAdddialog:function () {
                this.isShowingBox = true;
                this.dialogFormVisible =  true
            }
        },
        created:function(){
            $.post("${basePath}merchant/dept/togetDeptTree",{status:"01"}, function (json) {
                if(json.status == "success"){
                    layer.close(loadJigou);
                    var ztreeArr = new Array();
                    jigou_manage.ztreeData = json.t;
                    if(jigou_manage.ztreeData.length < 2){
                        jigou_manage.isShowAddBtnInfo = true;
                    }else {
                        jigou_manage.isShowAddBtnInfo = false;
                    }
                    ztreeArr = json.t;
//                    if(ztreeArr.length<2) jigou_manage.$message.warning('请先添加机构');
                    var treeObj = $.fn.zTree.init($("#treeDemo"), setting, ztreeArr);
                    treeObj.expandAll(true);
                    //默认展开所有节点

                }
            });
        }
    })
</script>
<style>
    .ztree{
        float: left;
    }
    .ztree li span.button.add {
        margin-left:2px;
        margin-right: -1px;
        background-position:-144px 0;
        vertical-align:top;
        *vertical-align:middle;

    }

    .addUsrtBtn{
        float: right;
        margin-right: 200px;
        background-color: #409EFF;
        border: 0;
        overflow: hidden;
        outline: none;
        color: #fff;
        -webkit-border-radius:5px;
        -moz-border-radius:5px;
        border-radius:5px;
        padding: 5px 7px;
    }
    .addUsrtBtn:active{
        background-color: #409Ecc;
    }
    .pullAllTemp{
        text-decoration: none;
        color: #ff4444;
    }
    .upload-demo{
        position: absolute;
        left: 160px;
        top: 0px;
    }
    #fileArea{
        height: 38px;
        position: absolute;
        right: 0;
        z-index: 10;
        opacity: 0;
    }
    #liulan{
        position: absolute;
        right: 0;
        z-index: 9;
    }
    .el-dialog__body{
        height: 150px;
    }
    #uploadForm{
        position: absolute;
        left: 220px;
        top: 0px;
    }
    .showFileName{
        text-align: right;
        width: 300px;
        position: absolute;
        top: 43px;
        right: 0;
    }
</style>